package com.example.smartcity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.io.IOException

/**
 * 文件上传 activity 头像上传
 * @author YSJ
 * @date 2021/4/18 : 15:22
 */
class UpLoadActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_up_load)

        findViewById<Button>(R.id.btn_up_load).setOnClickListener {
            checkPermission()
        }
    }


    /**
     * 检查权限
     */
    private fun checkPermission(){
        //申请权限（Android6.0及以上 需要动态申请危险权限）
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)  != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,  arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE),0)
        }else{
            pickPhoto()
        }
    }

    /**
     * 打开相册 这个是系统的媒体选择
     */
    private fun pickPhoto() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, 0XF1) // 打开相册
    }


    /**
     * 权限申请回掉
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode==0){
            if(permissions.isNotEmpty() &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                pickPhoto()
            }else{
                Toast.makeText(this,"权限已拒绝",Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 图片申请回调
     *
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==0XF1){
            val data1 = data?.data
            val path = data1?.path
            print(path)
            if (path.isNullOrBlank()){
                Toast.makeText(this,"请选择图片",Toast.LENGTH_LONG).show()
                return
            }
            //将 uri 资源 转行成 绝对路径的文件
            val uriToFile = uriToFile(this, data1!!)
            upLoadImage(uriToFile)
        }
    }


    /**
     * 上传文件
     */
    private fun upLoadImage(mFile: File?) {
        if (mFile==null){
            return
        }
        val client=OkHttpClient()
        val body:RequestBody= MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "file",
                mFile?.name,
                mFile?.asRequestBody("multipart/form-data".toMediaTypeOrNull())!!)
            .addFormDataPart("xxx","xxx") //其他参数
            .build()

        val request=Request.Builder()
            .post(body)
            .url("https://www.baidu.com")
            .build()

        client.newCall(request).enqueue(object :Callback{
            override fun onFailure(call: Call, e: IOException) {
                //上传失败
            }

            override fun onResponse(call: Call, response: Response) {
               //上传成功
            }
        })

    }
}